package com.example.web_project_xianyu.controller;

import com.example.web_project_xianyu.FileUpload;
import com.example.web_project_xianyu.entity.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.text.SimpleDateFormat;

@Controller
@RequestMapping("/market")
public class xianyu_controller {
    @Resource
    com.example.web_project_xianyu.mappers.userMapper userMapper;
    @Resource
    com.example.web_project_xianyu.mappers.productMapper productMapper;
    @Resource
    com.example.web_project_xianyu.mappers.starMapper starMapper;
    @Resource
    com.example.web_project_xianyu.mappers.likeMapper likeMapper;
    @Resource
    com.example.web_project_xianyu.mappers.commentMapper commentMapper;
    @Resource
    com.example.web_project_xianyu.mappers.chatMapper chatMapper;
    //用户注册提交
    @PostMapping(path="/register")
    String register_func(@RequestParam String username,@RequestParam String password, ServletRequest servletRequest,Model model){
        List<User>users=userMapper.select_all();//获取此时用户表中的所有表项
        int flag=1;
        for(int i=0;i<users.size()&&flag==1;i++){//遍历所有表项
            if(username.equals(users.get(i).userName)){
                flag=0;//若提交的用户名在表项中已存在，则置位
            }
        }
        //如果表项中不存在此用户名，可以注册
        if(flag==1){
            User user=new User(username,password);
            userMapper.insert_user(user);//将提交的用户名和密码加入用户表
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            HttpSession session = req.getSession();
            session.setAttribute("user_id",user.userId);//注册成功则视为已登录，在session中添加值
            List<Product> products_get= productMapper.select_all_product();
            List<Product> products=new LinkedList<>();
            model.addAttribute("products",products_get);
            return "index";//返回咸鱼首页
        }
        return "REGISTER_FAILED";//注册失败
    }
    @GetMapping("/register")
    String get_register(){
        return "register";
    }

    //用户登录
    @PostMapping(path="/login")
    String login_func(@RequestParam String username,@RequestParam String password, ServletRequest servletRequest,Model model){
        User user=userMapper.select_by_name(username);//通过用户名查询并获取用户表中的表项
        if(user!=null){//返回结果不为空
            if(user.password.equals(password)) {
                HttpServletRequest req = (HttpServletRequest) servletRequest;
                HttpSession session = req.getSession();
                //若此前已登录过一个用户，先清空session值
                if(session.getAttribute("user_id")!=null){
                    session.removeAttribute("user_id");
                }
                session.setAttribute("user_id", user.userId);
                //商品表中获取所有的商品信息，传递给前端
                List<Product> products_get= productMapper.select_all_product();
                List<Product> products=new LinkedList<>();
                model.addAttribute("products",products_get);
                return "index";//返回咸鱼首页
            }
        }
        //若返回结果为空或得到的密码与用户提交的密码不匹配
        return "LOGIN_FAILED";//登录失败
    }

    @GetMapping("/login")
    String get_login(){
        return "login";
    }

    //用户登出
    @GetMapping("/logout")
    String logout(ServletRequest servletRequest){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){
            session.removeAttribute("user_id");
        }
        return "login";//首页登录，templates暂时还没对象
    }

    //商品查看，获取咸鱼首页
    @GetMapping("/index")
    String get_index(Model model){
        //获取全部商品传递给前端
        List<Product> products_get= productMapper.select_all_product();
        List<Product> products=new LinkedList<>();
        model.addAttribute("products",products_get);
        return "index";
    }
    //按类别查看
    @GetMapping(path="/product",params = {"class_type"})
    String get_product_by_class(@RequestParam int class_type, Model model){
        List<Product> products=productMapper.select_product_bytype(class_type);//数据库中检索商品类别为对应参数值的商品
        switch (class_type){
            case 1:
                model.addAttribute("search_info","衣服");
                break;
            case 2:
                model.addAttribute("search_info","食品");
                break;
            case 3:
                model.addAttribute("search_info","电子产品");
                break;
            case 4:
                model.addAttribute("search_info","书籍");
                break;
            case 5:
                model.addAttribute("search_info","化妆品");
                break;
            case 6:
                model.addAttribute("search_info","其他");
                break;
        }
        model.addAttribute("products",products);
        model.addAttribute("type",1);
        model.addAttribute("later_info",class_type);
        return "search_result";//分类的商品界面
    }

    //按关键字搜索
    @GetMapping(path="/product",params = {"keyword"})
    String get_product_by_keyword(@RequestParam String keyword, Model model) {
        List<Product> products=productMapper.select_all_product();//从商品表中获取所有商品表项
        List<Product> result=new LinkedList<>();
        for(int i=0;i<products.size();i++){
            //遍历表项，若此表项的商品名包含关键字，则将其加入待返回的商品数组中。
            if(products.get(i).productName.indexOf(keyword)!=-1){
                result.add(products.get(i));
            }
        }
        model.addAttribute("search_info",keyword);
        model.addAttribute("later_info",keyword);
        model.addAttribute("products",result);
        model.addAttribute("result_num",result.size());
        model.addAttribute("type",2);
        return "search_result";//搜索的页面结果
    }


    //在前二者的基础上进行排序,此前是类别
    @GetMapping(path = "/product",params = {"sort_prev=1"})
    String class_type_sort(@RequestParam int later_info, @RequestParam int sort_type ,Model model){
        //根据传递过来的参数重新进行商品检索操作，具体检索逻辑与get_product_by_class相同
        List<Product> products=productMapper.select_product_bytype(later_info);
        //进行排序并返回
        if(sort_type==2) {//按点赞数排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getLike()-product1.getLike();
                }
            });
        }
        else if(sort_type==3){//按评论数排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getCommentNumber()-product1.getCommentNumber();
                }
            });
        }
        else if(sort_type==1){//按发布时间排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getTime().compareTo(product1.getTime());
                }
            });
        }
        //由于与get_product_by_class返回界面相同，且有可能进行多次排序操作，为前端提供的变量需与get_product_by_class相同
        model.addAttribute("products",products);
        model.addAttribute("type",1);
        model.addAttribute("later_info",later_info);
        switch (later_info){
            case 1:
                model.addAttribute("search_info","衣服");
                break;
            case 2:
                model.addAttribute("search_info","食品");
                break;
            case 3:
                model.addAttribute("search_info","电子产品");
                break;
            case 4:
                model.addAttribute("search_info","书籍");
                break;
            case 5:
                model.addAttribute("search_info","化妆品");
                break;
            case 6:
                model.addAttribute("search_info","其他");
                break;
            default:
                break;
        }//
        return "search_result";
    }

    //在前二者的基础上进行排序,此前是关键字
    @GetMapping(path = "/product",params = {"sort_prev=2"})
    String keyword_sort(@RequestParam String later_info, @RequestParam int sort_type,Model model){
        //根据传递过来的参数重新进行商品检索操作，具体检索逻辑与get_product_by_keyword相同
        List<Product> products=productMapper.select_all_product();
        List<Product> result=new LinkedList<>();
        for(int i=0;i<result.size();i++){
            if(result.get(i).productName.indexOf(later_info)!=-1){
                products.add(result.get(i));
            }
        }
        //进行排序并返回
        if(sort_type==2) {//按点赞数排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getLike()-product1.getLike();
                }
            });
        }
        else if(sort_type==3){//按评论数排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getCommentNumber()-product1.getCommentNumber();
                }
            });
        }
        else if(sort_type==1){//按时间排序
            Collections.sort(products, new Comparator<Product>() {
                public int compare(Product product1, Product product2) {
                    return product2.getTime().compareTo(product1.getTime());
                }
            });
        }
        //由于与get_product_by_keyword返回界面相同，且有可能进行多次排序操作，为前端提供的变量需与get_product_by_keyword相同
        model.addAttribute("search_info",later_info);
        model.addAttribute("products",products);
        model.addAttribute("result_num",products.size());
        model.addAttribute("later_info",later_info);
        model.addAttribute("type",2);
        return "search_result";
    }


    //查看商品详情
    @GetMapping("/product/info")
    String get_product_info(@RequestParam int product_id,ServletRequest servletRequest,Model model){
        //由于商品详情页包括了商品详细评论、用户点赞按钮、用户收藏按钮、对商家发起聊天等多元素，后端需根据前端的需求，从多个表中获取对应的信息。
        //获根据提交的参数product_id从商品表中查询此商品的详细信息；
        Product product=productMapper.select_product_by_id(product_id);
        //根据提交的参数product_id从评论表中查询对此商品的评论表项；
        List<Comment> comments=commentMapper.get_product_comment(product_id);
        Collections.sort(comments, new Comparator<Comment>() {
            public int compare(Comment comment1, Comment comment2) {
                return comment1.getTime().compareTo(comment2.getTime());
            }
        });//评论时间升序
        for(int i=0;i<comments.size();i++){
            User user=userMapper.select_by_id(comments.get(i).userId);
        }
        //若没有评论，返回一个包含"暂时没有评论"的空评论信息。
        if(comments.size()==0) {
            Comment comment_empty=new Comment(0,0," ","暂时没有评论","");
            comments.add(comment_empty);
        }
        model.addAttribute("product",product);
        model.addAttribute("comments",comments);
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        //根据提交的参数product_id和当前的session值，从点赞表和收藏表中寻找包含此用户id和商品id的表项，获取此用户是否已点赞或已收藏的信息；
        if(session.getAttribute("user_id")!=null){
            int user_id = (int) session.getAttribute("user_id");
            star_like_entity star=starMapper.get_star_by_user_and_product_id(user_id,product_id);
            star_like_entity like=likeMapper.get_like_by_user_and_product_id(user_id,product_id);
            if(star!=null)//若用户已收藏
                model.addAttribute("star","取消收藏");
            else//若用户未收藏
                model.addAttribute("star","收藏");
            if(like!=null)//若用户已点赞
                model.addAttribute("like","取消点赞");
            else//若用户未点赞
                model.addAttribute("like","点赞");
            return "product_info";//物品详情页
        }
        model.addAttribute("star","收藏");
        model.addAttribute("like","点赞");
        //将上述所有信息传递给前端，返回物品详情页。
        return "product_info";//物品详情页
    }

    //添加商品评论
    @PostMapping(path = "/product/comment")
    String add_comment(@RequestParam int product_id,@RequestParam String text,ServletRequest servletRequest,Model model) {
        //需先登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){//已登录
            //获取当前系统时间
            int user_id=(int)session.getAttribute("user_id");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
            String time = format.format(new Date());
            User user=userMapper.select_by_id(user_id);
            if(!text.equals("")) {
                commentMapper.add_comment(user_id, user.userName, product_id, time, text);//添加评论
                productMapper.commentNumber_add(product_id);//更新商品表中此商品id的评论数为原评论数+1
            }
            //由于提交评论后需要刷新商品详情页，且实现时未使用ajax，故需要进行相当于重新请求一遍商品详情页的操作
            //此下的逻辑与get_product_info函数相同
            Product product=productMapper.select_product_by_id(product_id);
            List<Comment> comments=commentMapper.get_product_comment(product_id);
            Collections.sort(comments, new Comparator<Comment>() {
                public int compare(Comment comment1, Comment comment2) {
                    return comment1.getTime().compareTo(comment2.getTime());
                }
            });//评论时间升序
            if(comments.size()==0) {
                Comment comment_empty=new Comment(0,0," ","暂时没有评论","");
                comments.add(comment_empty);
            }
            model.addAttribute("product",product);
            model.addAttribute("comments",comments);
            star_like_entity star=starMapper.get_star_by_user_and_product_id(user_id,product_id);
            star_like_entity like=likeMapper.get_like_by_user_and_product_id(user_id,product_id);
            if(star!=null)
                model.addAttribute("star","取消收藏");
            else
                model.addAttribute("star","收藏");
            if(like!=null)
                model.addAttribute("like","取消点赞");
            else
                model.addAttribute("like","点赞");
            //返回与get_product_info函数相同的数据给前端，跳转至商品详情页。
            return "product_info";//物品详情页
        }
        return "PLEASE_LOGIN";//需先登录
    }

    //商品收藏
    @GetMapping(path="/product/star")
    String star_product(@RequestParam int product_id,ServletRequest servletRequest,Model model){
        //需先登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){//已登录
            model.addAttribute("product_id",product_id);
            int user_id=(int)session.getAttribute("user_id");
            //从收藏表中搜索匹配此商品id和用户id的表项。
            star_like_entity star=starMapper.get_star_by_user_and_product_id(user_id,product_id);
            if(star==null){//此前未收藏
                starMapper.add_star(user_id,product_id);//从收藏表中删除此表项
                return "STAR_ADD";
            }
            else//此前已收藏
                starMapper.delete_star(user_id,product_id);//从收藏表中添加此商品id和用户id的表项。
            return "STAR_DELETE";//物品详情页
        }
        return "PLEASE_LOGIN";
    }

    //商品点赞
    @GetMapping(path="/product/like")
    String like_product(@RequestParam int product_id,ServletRequest servletRequest,Model model){
        //需先登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){//已登录
            int user_id=(int)session.getAttribute("user_id");
            model.addAttribute("product_id",product_id);
            //从点赞表中搜索匹配此商品id和用户id的表项。
            star_like_entity like=likeMapper.get_like_by_user_and_product_id(user_id,product_id);
            if(like==null){//此前未点赞
                likeMapper.add_like(user_id,product_id);//向点赞表中添加此商品id和用户id的表项。
                productMapper.like_add(product_id);//更新商品表中此商品id的点赞数（+1）
                return "LIKE_ADD";
            }
            else {
                likeMapper.delete_like(user_id, product_id);//从点赞表中删除此表项
                productMapper.like_remove(product_id);//更新商品表中此商品id的点赞数（-1）
                return "LIKE_DELETE";
            }
        }
        return "PLEASE_LOGIN";
    }

    //获取我的页面
    @GetMapping("/my")
    String get_my(Model model, ServletRequest servletRequest){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){
            int user_id=(int)session.getAttribute("user_id");
            //获取本人管理的列表
            List<Product> my_products=productMapper.select_product_by_user_id(user_id);//根据用户id从商品表中获取user_id字段为此用户id的商品。
            model.addAttribute("my_products",my_products);
            //获取本人用户名
            User user=userMapper.select_by_id(user_id);//根据此用户id从用户表中获取此id对应的用户名
            model.addAttribute("user_name",user.userName);
            return "my_page";//返回我的页面
        }
        return "PLEASE_LOGIN";//未登录
    }

    //获取收藏
    @GetMapping("/my/collect")
    String get_my_collect(Model model, ServletRequest servletRequest){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id=(int)session.getAttribute("user_id");
            //获取收藏列表
            //从收藏表中搜索用户id与当前登录的用户id相匹配的表项，获取收藏的商品id
            List<star_like_entity>star_entity=starMapper.get_star_by_userid(user_id);
            List<Product> star_products = new LinkedList<>();
            for(int i=0;i<star_entity.size();i++){
                int star_product_id=star_entity.get(i).productId;
                //从商品表中，搜索商品表中的商品的id，与此前得到的表项结果中用户所收藏的商品id相匹配的商品表项
                star_products.add(productMapper.select_product_by_id(star_product_id));
            }
            //将得到的商品表项列表返回给前端。
            model.addAttribute("star_products",star_products);
            return "my_collect";//返回管理页面
        }
        return "PLEASE_LOGIN";//未登录
    }
    //从我的收藏里面取消收藏
    @GetMapping("/my/deletestar")
    String del_star_frommy(@RequestParam int product_id,ServletRequest servletRequest,Model model){
        //需先登录
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null){//已登录
            model.addAttribute("product_id",product_id);
            int user_id=(int)session.getAttribute("user_id");
            //从收藏表中直接删除此商品id与当前登录的用户id相匹配的表项
            starMapper.delete_star(user_id,product_id);
            return "STAR_DELETE_FROM_MYCOLLECT";//物品详情页
        }
        return "PLEASE_LOGIN";
    }

    //添加商品,返回添加页面
    @GetMapping(path="/product/add")
    String add_page(ServletRequest servletRequest){
        return "new_product";
    }

    //添加商品
    @PostMapping(path="/product/add")
    String add_product(@RequestParam String product_name, @RequestParam int product_class, @RequestParam String product_describe,
                       @RequestParam("picture")MultipartFile image_file,@RequestParam int store,@RequestParam float price, ServletRequest servletRequest
                ,Model model) {
        Product product=new Product();
        //判断所添加的商品信息是否合法
        if(!product_name.equals("")&&!product_describe.equals("")){
            if(store>0&&price>0){
                HttpServletRequest req = (HttpServletRequest) servletRequest;
                HttpSession session = req.getSession();
                if(session.getAttribute("user_id")!=null) {
                    int user_id = (int) session.getAttribute("user_id");
                    product.productName = product_name;
                    product.productClass = product_class;
                    product.userId = user_id;
                    product.commentNumber = 0;
                    product.like = 0;
                    product.store = store;
                    product.price = price;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
                    String time = format.format(new Date());
                    product.time = time;
                    FileUpload fileUpload=new FileUpload();
                    product.picture=fileUpload.upload_file(image_file,"/Users/xubin/Desktop/web-book-images");
                    product.productDescribe=product_describe;
                    productMapper.add_product(product);//构造完整的商品表对应的实体对象插入商品表中
                    return "ADD_SUCCESS";
                }
                return "PLEASE_LOGIN";//未登录
            }
        }
        return "ADD_FAIL";//添加失败
    }

    @GetMapping(path = "/product/delete")
    String delete_product(@RequestParam int product_id, ServletRequest servletRequest) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id = (int) session.getAttribute("user_id");
            //从商品表中搜索此商品id对应的商品表项
            Product product=productMapper.select_product_by_id(product_id);
            int owner_id=product.userId;
            if(owner_id==user_id) {//若表项中储存的拥有者id与当前登录的用户id相同
                productMapper.delete_product(product_id);
                //注意此时还要从所有的like_table和star_table/comment_tabld/chat_table删去此商品
                chatMapper.delete_product(product_id);
                commentMapper.delete_product(product_id);
                likeMapper.delete_product(product_id);
                starMapper.delete_product(product_id);
                return "DELETE_PRODUCT_SUCC";
            }
            return "DELETE_PRODUCT_FAIL";
        }
        return "PLEASE_LOGIN";
    }

    //消息服务
    //发起消息请求后获取消息
    @GetMapping("/chat/to")
    String chat_toseller(@RequestParam int product_id, @RequestParam int to_id,ServletRequest servletRequest,Model model){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id = (int) session.getAttribute("user_id");
            System.out.println(product_id);
            //从消息表中查询此商品id对应的、收发双方的用户id其一为当前登录用户的所有消息（获取历史消息）
            List<Chat> chats=chatMapper.get_all_chat_of_one(product_id,user_id);
            Collections.sort(chats, new Comparator<Chat>() {
                public int compare(Chat chat1, Chat chat2) {
                    return chat1.getTime().compareTo(chat2.getTime());
                }
            });//时间升序
            List<Chat> from=new LinkedList<>();
            List<Chat> to=new LinkedList<>();
            //根据消息表中fromid字段和toid字段判断收发方向并进行分类;
            for(int i=0;i<chats.size();i++){
                if(chats.get(i).fromId==user_id) {
                    from.add(chats.get(i));//是我发过去的
                    System.out.println(chats.get(i).chatText);
                }
                else{
                    to.add(chats.get(i));//是对面发过来的
                    System.out.println(chats.get(i).chatText);
                }

            }
            model.addAttribute("product_id",product_id);
            model.addAttribute("to_id",to_id);
            model.addAttribute("tos",to);
            model.addAttribute("froms",from);
            //返回私聊页面。
            return "chat_record";
        }
        return "PLEASE_LOGIN";
    }

    //这个商品是自己管理的商品
    @GetMapping("/chat/tobuyer")
    String start_chat(@RequestParam int product_id, @RequestParam int buyer_id,ServletRequest servletRequest,Model model) {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id = (int) session.getAttribute("user_id");
            //消息表中查询此商品id对应的、收者与发者对应买家id和当前用户id，或发者与收者对应买家id和当前用户id的所有消息（获取历史消息）。
            List<Chat> chats=chatMapper.get_all_chat_of_one(product_id,buyer_id);
            Collections.sort(chats, new Comparator<Chat>() {
                public int compare(Chat chat1, Chat chat2) {
                    return chat1.getTime().compareTo(chat2.getTime());
                }
            });//时间升序
            List<Chat> from=new LinkedList<>();
            List<Chat> to=new LinkedList<>();
            //根据消息表中fromid字段和toid字段判断收发方向并进行分类;
            for(int i=0;i<chats.size();i++){
                if(chats.get(i).fromId==user_id) {
                    from.add(chats.get(i));//是我发过去的
                    System.out.println(chats.get(i).chatText);
                }
                else{
                    to.add(chats.get(i));//是对面发过来的
                    System.out.println(chats.get(i).chatText);
                }
                User user=userMapper.select_by_id(buyer_id);
                model.addAttribute("seller_name",user.userName);
                model.addAttribute("product_id",product_id);
                model.addAttribute("to_id",buyer_id);
                model.addAttribute("tos",to);
                model.addAttribute("froms",from);
            }
            return "chat_record";
        }
        return "PLEASE_LOGIN";
    }

    //提交信息
    @PostMapping("/chat/to")
    String add_chat(@RequestParam int product_id,@RequestParam int to_id,@RequestParam String chat_text, ServletRequest servletRequest,Model model){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id = (int) session.getAttribute("user_id");
            //聊天文本合法
            if(!chat_text.equals("")) {
                //Product product = productMapper.select_product_by_id(product_id);
                //获取当前时间
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm");
                String time = format.format(new Date());
                Chat chat = new Chat(to_id, user_id, chat_text, time, product_id);
                chatMapper.add_chat(chat);//根据得到的参数构造完整的聊天表的实体对象，在聊天表中插入此实体对象的表项
            }
            List<Chat> chats=new LinkedList<>();
            //重新获取这二者的所有历史消息,相当于重新发起一次页面请求
            if(user_id==productMapper.select_product_by_id(product_id).userId){//如果这个商品是自己管理的商品，复制/chat/tobuyer的页面逻辑
                chats=chatMapper.get_all_chat_of_one(product_id,to_id);//获取buyer对自己发的和自己对buyer发的所有聊天记录
            }
            else
                chats=chatMapper.get_all_chat_of_one(product_id,user_id);

            Collections.sort(chats, new Comparator<Chat>() {
                public int compare(Chat chat1, Chat chat2) {
                    return chat1.getTime().compareTo(chat2.getTime());
                }
            });


            List<Chat> from=new LinkedList<>();
            List<Chat> to=new LinkedList<>();
            Chat emptychat=new Chat(-1,-1,"","",-1);
            for(int i=0;i<chats.size();i++){
                if(chats.get(i).fromId==user_id) {
                    from.add(chats.get(i));//是我发过去的
                    System.out.println(chats.get(i).chatText);
                }
                else{
                    to.add(chats.get(i));//是对面发过来的
                    //from.add(emptychat);
                    System.out.println(chats.get(i).chatText);
                }

            }
            model.addAttribute("product_id",product_id);
            model.addAttribute("to_id",to_id);
            model.addAttribute("tos",to);
            model.addAttribute("froms",from);
            return "chat_record";//返回聊天记录页面
        }
        return "PLEASE_LOGIN";

    }

    //消息记录页面请求
    @GetMapping("/chat")
    String get_my_chat_page(ServletRequest servletRequest,Model model){
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        if(session.getAttribute("user_id")!=null) {
            int user_id = (int) session.getAttribute("user_id");
            //获取自己发送过的的聊天记录（fromid为当前登录的用户id） 去重得到非重复的productId
            List<Chat> product_chated=chatMapper.get_my_chated_product(user_id);
            List<Chat> after_removed=new LinkedList<>();
            //去除自己管理的商品
            //遍历聊天记录对应的商品id，从商品表中搜索商品id对应的用户id，若用户id与自身id相同，则去除；
            for(int i=0;i<product_chated.size();i++){
                Product is_in=productMapper.select_product_by_id(product_chated.get(i).productId);
                if (is_in.userId!=user_id)
                    after_removed.add(product_chated.get(i));
            }
            List<Integer> product_ids=new LinkedList<>();
            List<Product> products=new LinkedList<>();
            int flag=1;
            //再次进行去重，去除包含相同的商品id的聊天记录，得到仅包含不同的商品id的商品列表
            for(int i=0;i<after_removed.size();i++){
                for(int j=0;j<product_ids.size()&&flag==1;j++){
                    if(after_removed.get(i).productId==product_ids.get(j))
                        flag=0;
                }
                if(flag==1) {
                    product_ids.add(after_removed.get(i).productId);
                    products.add(productMapper.select_product_by_id(after_removed.get(i).productId));
                }
                else
                    flag=1;//置位
            }
            //此商品列表则是用户发起过聊天的商品列表。
            model.addAttribute("chated_products",products);
            //获取自己管理的商品列表
            List<Product> my_products=productMapper.select_product_by_user_id(user_id);
            List<Integer> processed_chatid=new LinkedList<>();//已去重的from_id
            List<Product> products_results=new LinkedList<>();//总列表
            List<User> peoples_results=new LinkedList<>();//总列表
            List<buyer_productid_class> informations=new LinkedList<>();
            for(int i=0;i<my_products.size();i++){
                //找到本product下发起过聊天的id
                processed_chatid.clear();//一件商品去重一次
                flag=1;
                List<Chat> all_chated_buyerid=chatMapper.get_chat_by_product_id(my_products.get(i).productId,user_id);
                for(int j=0;j<all_chated_buyerid.size()&&flag==1;j++){//进行去重，去除重复的fromid
                    for(int k=0;k<processed_chatid.size()&&flag==1;k++){
                        if(processed_chatid.get(k)==all_chated_buyerid.get(j).fromId)//from_id已存在
                            flag=0;
                    }
                    if(flag==1) {//fromid未加入过
                        processed_chatid.add(all_chated_buyerid.get(j).fromId);
                        products_results.add(productMapper.select_product_by_id(all_chated_buyerid.get(j).productId));//记录此时对应的商品
                        peoples_results.add(userMapper.select_by_id(all_chated_buyerid.get(j).fromId));//记录此时对方的信息
                        buyer_productid_class temp=new buyer_productid_class();
                        temp.buyer_id=all_chated_buyerid.get(j).fromId;
                        temp.buyer_name=userMapper.select_by_id(all_chated_buyerid.get(j).fromId).userName;
                        temp.product_id=all_chated_buyerid.get(j).productId;
                        informations.add(temp);
                    }
                    else
                        flag=1;//置位
                }
            }
            model.addAttribute("informations",informations);
            model.addAttribute("seller_products",products_results);
            model.addAttribute("chated_user",peoples_results);
            return "chat_window";
        }
        return "PLEASE_LOGIN";
    }

}
